import { Component, OnDestroy, OnInit } from '@angular/core';
import { AutopartsService } from '@core/services/autoparts/autoparts.service';
import { Subject, Subscription } from 'rxjs';
import { AutopartsViewService } from '@core/services/autoparts/autoparts.view.service';
import { ApesMessageService } from '@shared/apes/message';
import { debounce, debounceTime } from 'rxjs/operators';
import { HttpService } from '@core/services/http/http.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';

interface Item {
  id: string;
  name: string;
  imageUrls: string;
  realSrc: string;
  [propName: string]: any;
}

@Component({
  selector: 'epc-level-list',
  templateUrl: './epc-level-list.component.html',
  styleUrls: ['./epc-level-list.component.scss']
})
export class EpcLevelListComponent implements OnInit, OnDestroy {

  private selectSubgroup$ = new Subject();

  private subscription: Subscription;

  private currentActive = 0;

  data: any = {};

  constructor(
    private autopartsService: AutopartsService,
    private  autopartsViewService: AutopartsViewService,
    private msgService: ApesMessageService,
    private http: HttpClient
  ) {
  }

  ngOnInit(): void {
    this.subscription = this.autopartsViewService.subgroupChange$.subscribe(data => {
      this.data = data;
      this.currentActive = 0;
      this.resolveData(this.data);
    });

    this.selectSubgroup$.pipe(debounceTime(500)).subscribe((value:any) => {
      this.currentActive = value.index;
      this.autopartsService.selectSubgroup$.next(value.item);
    });

    this.autopartsService.nextSubgroup$.subscribe(() => {
      let nextIndex = this.currentActive + 1;
      if( nextIndex == this.data.data.length ) {
        this.msgService.warning("没有额外的子组");
        return
      } else {
        this.handleClick(null, this.data.data[nextIndex], nextIndex);
      }
    })
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

  handleClick($event, item, index) {
    // 限制重复点击
    this.selectSubgroup$.next({index,item});
  }

  resolveData(data) {
    if (data && data.data) {
      let array = data.data;
      for (let i = 0, len = array.length; i < len; i++) {
        let imageUrls = array[i].urls ? array[i].urls.split(',') : [];
        imageUrls = imageUrls.map( str => `remoteEpcImage/${array[i].epcVersion}/${str}`)
        array[i].imageUrls = imageUrls;
        this.getImageUrl(array[i]);
      }
    }
  }

  getImageUrl(item){
    if (!(item.imageUrls && item.imageUrls[0])) return;
    if (!/\.tif$/.test(item.imageUrls[0]) && !/\.TIF$/.test(item.imageUrls[0])) item.realSrc = item.imageUrls[0];

    this.http.request("GET", item.imageUrls[0], {
      responseType:'arraybuffer',
    }).subscribe(response => {
        var tiff = new Tiff({buffer: response});
        item.realSrc = tiff.toDataURL();
    });
  }
}
